# =================================================================================
# remove everything
rm(list=ls())

# ---------------------------------------------------------------------
# Drop outliers in dataset "Data" according to the "v"th column
# at each percentage "p" at bottom and top. The default value of
# p is 0.005. v is a vector of numbers.
# ---------------------------------------------------------------------

outlier <- function(Data, v, p=0.005) {
  out <- c()
  for(i in v) {
    out <- rbind(out, quantile(Data[,i], probs=c(p, 1-p)))
  }
  j <- 1
  for(i in v) {
    Data <- Data[Data[,i]>out[j,1] & Data[,i]<out[j,2], ]; print(dim(Data))
    j <- j+1
  }
  return(Data)
}
# ---------------------------------------------------------------------

# Load packages
library(foreign)
library(plm) # ---------------

# Load data
Data <- read.dta('Ind39.dta')

Data <- outlier(Data, which(names(Data)=="sm"), p=0.005)

# Delete obs according to variable "Foreign"
Data <- subset(Data, F1>=0 & F1<=1 & !is.na(Province) & sm<=1)

# Generate weights & variables related to weights
for(i in 1:nrow(Data)) {
  s1.t <- (Data$F1 == 0)*(Data$Year==Data$Year[i])*(Data$Province==Data$Province[i]); s1.t[i] <- 0
  s1.b <- sum(s1.t)
  s1 <- if(s1.b>0) s1.t/s1.b else rep(0, length(s1.t));
  s2.t <- (Data$F1 > 0)*(Data$Year==Data$Year[i])*(Data$Province==Data$Province[i]); s2.t[i] <- 0
  s2.b <- sum(s2.t)
  s2 <- if(s2.b>0) s2.t/s2.b else rep(0, length(s2.t))
  Data$w1k1[i] <- sum(s1*Data$k1); Data$w1m1[i] <- sum(s1*Data$m1, na.rm = TRUE); Data$w1l1[i] <- sum(s1*Data$l1, na.rm = TRUE)
  Data$w2k1[i] <- sum(s2*Data$k1); Data$w2m1[i] <- sum(s2*Data$m1, na.rm = TRUE); Data$w2l1[i] <- sum(s2*Data$l1, na.rm = TRUE)
}

# Generate year dummies
Data$TD <- model.matrix(~as.factor(Data$Year)-1); Data$TD1 <- model.matrix(~as.factor(Data$Year-1)-1)[,-1]

# Calculate the length of loop
firm.list <- unique(Data$Firm)
R <- ceiling(length(firm.list)/50)

# empty obj.
JKpw <- JKpF <- JKps1w <- JKps2w <- JKptil1 <- JKptil2 <- JKbeta <- JKcoef <- c()

for(ii in 1:R) {
  
  print(ii)
  # get jackknife samples
  from <- 50*(ii-1)+1; to <- 50*ii
  index <- Data$Firm %in% firm.list[from:to]
  D.jk <- Data[!index, ]
  
  # =============================================
  # Step One
  h.lnbe <- mean(log(D.jk$sm)); h.eta <- - log(D.jk$sm) + h.lnbe; h.e <- mean(exp(h.eta))
  h.betam <- exp(h.lnbe)/h.e
  
  # =============================================
  # Step Two
  # Define functions: "wphi" and "phi"
  w1phi <- function(beta) {
    (1-h.betam)*D.jk$w1m1 - h.lnbe - log(D.jk$ppi1/D.jk$ppii1) - beta[1]*D.jk$w1k1 - beta[2]*D.jk$w1l1 - D.jk$TD1%*%beta[3:10]
  }
  
  w2phi <- function(beta) {
    (1-h.betam)*D.jk$w2m1 - h.lnbe - log(D.jk$ppi1/D.jk$ppii1) - beta[1]*D.jk$w2k1 - beta[2]*D.jk$w2l1 - D.jk$TD1%*%beta[3:10]
  }
  
  phi <- function(beta) {
    (1-h.betam)*D.jk$m1 - h.lnbe - log(D.jk$ppi1/D.jk$ppii1) - beta[1]*D.jk$k1 - beta[2]*D.jk$l1 - D.jk$TD1%*%beta[3:10]
  }
  
  
  # -----------------------------------------------
  # Optimization
  objfn <- function(beta){
    y.star <- D.jk$y - h.betam*D.jk$m - beta[1]*D.jk$k - beta[2]*D.jk$l - D.jk$TD%*%beta[3:11]
    p1 <- as.vector(phi(beta)); p2 <- as.vector(w1phi(beta)); p3 <- as.vector(w2phi(beta))
    var.poly <- poly(cbind(p1, D.jk$F1, p2, p3), degree = 2, raw = TRUE)
    mod1 <- lm(as.vector(y.star)~var.poly)
    OBJ <- sum(mod1$residuals^2)
    return(OBJ)
  }
  
  set.seed(1)
  initial <- c(0.05, 0.1, 0.05, 0,0,0,0,0,0,0,0,0)
  target <- optim(initial, objfn, method = "Nelder-Mead")
  
  # results - elas
  h.betak <- target$par[1]; h.betal <- target$par[2]
  
  G.coef <- function(beta){
    y.star <- D.jk$y - h.betam*D.jk$m - beta[1]*D.jk$k - beta[2]*D.jk$l - D.jk$TD%*%beta[3:11]
    p1 <- as.vector(phi(beta)); p2 <- as.vector(w1phi(beta)); p3 <- as.vector(w2phi(beta))
    var.poly <- poly(cbind(p1, D.jk$F1, p2, p3), degree = 2, raw = TRUE)
    mod1 <- lm(as.vector(y.star)~var.poly)
    return(mod1$coef)
  }
  # results - partial effects
  coef <- G.coef(target$par)[2:15]
  
  # Define functions: "wphi" and "phi" for the full sample
  w1phi <- function(beta) {
    (1-h.betam)*Data$w1m1 - h.lnbe - log(Data$ppi1/Data$ppii1) - beta[1]*Data$w1k1 - beta[2]*Data$w1l1 - Data$TD1%*%beta[3:10]
  }
  
  w2phi <- function(beta) {
    (1-h.betam)*Data$w2m1 - h.lnbe - log(Data$ppi1/Data$ppii1) - beta[1]*Data$w2k1 - beta[2]*Data$w2l1 - Data$TD1%*%beta[3:10]
  }
  
  phi <- function(beta) {
    (1-h.betam)*Data$m1 - h.lnbe - log(Data$ppi1/Data$ppii1) - beta[1]*Data$k1 - beta[2]*Data$l1 - Data$TD1%*%beta[3:10]
  }
  
  w1 <- as.vector(phi(target$par)); s1w1 <- as.vector(w1phi(target$par)); s2w1 <- as.vector(w2phi(target$par))
  
  p.w  <- coef[1] + 2*coef[2]*w1 + coef[4]*Data$F1 + coef[7]*s1w1 + coef[11]*s2w1
  p.F  <- coef[3] + coef[4]*w1 + 2*coef[5]*Data$F1 + coef[8]*s1w1 + coef[12]*s2w1
  p.s1w1 <- coef[6] + coef[7]*w1 + coef[8]*Data$F1 + 2*coef[9]*s1w1 + coef[13]*s2w1
  p.s2w1 <- coef[10] + coef[11]*w1 + coef[12]*Data$F1 + coef[13]*s1w1 + 2*coef[14]*s2w1
  
  
  # TIL
  D <- data.frame(Data[,c('Firm','Year','Province')], pw=p.w, pF=p.F, ps1w=p.s1w1, ps2w=p.s2w1)
  D <- pdata.frame(D, index = c("Firm", "Year"))
  D$pF1 <- lag(D$pF, 1); 
  D$DF1 <- Data$F1 == 0
  
  D$temp1 <- ave(D$pF1*D$DF1, D$Year, D$Province, FUN = function(x) sum(x, na.rm = TRUE))
  D$temp1[!is.na(D$pF1)] <- D$temp1[!is.na(D$pF1)] - (D$pF1*D$DF1)[!is.na(D$pF1)]
  D$temp2 <- ave((!is.na(D$pF1))*D$DF1, D$Year, D$Province, FUN = function(x) sum(x, na.rm = TRUE))
  D$temp2[!is.na(D$pF1)] <- D$temp2[!is.na(D$pF1)] - 1
  D$sp=D$temp1/D$temp2
  p.til1 <- as.numeric(D$ps1w*D$sp); 
  
  D$temp1 <- ave(D$pF1*(!D$DF1), D$Year, D$Province, FUN = function(x) sum(x, na.rm = TRUE))
  D$temp1[!is.na(D$pF1)] <- D$temp1[!is.na(D$pF1)] - (D$pF1*(!D$DF1))[!is.na(D$pF1)]
  D$temp2 <- ave((!is.na(D$pF1))*(!D$DF1), D$Year, D$Province, FUN = function(x) sum(x, na.rm = TRUE))
  D$temp2[!is.na(D$pF1) & D$temp2>0] <- D$temp2[!is.na(D$pF1) & D$temp2>0] - 1
  D$sp=D$temp1/D$temp2; D$sp[abs(D$sp)==Inf]<-NA
  p.til2 <- as.numeric(D$ps2w*D$sp); 
  
  # Store bootstrap results
  JKpw <- cbind(JKpw, p.w); JKpF <- cbind(JKpF, p.F); 
  JKps1w <- cbind(JKps1w, p.s1w1); JKps2w <- cbind(JKps2w, p.s2w1); JKptil1 <- cbind(JKptil1, p.til1); JKptil2 <- cbind(JKptil2, p.til2)
  JKbeta <- cbind(JKbeta, c(h.betak, h.betal, h.betam))
  JKcoef <- cbind(JKcoef, coef)
  
}

apply(JKbeta, MARGIN = 1, sd)
summary(JKpw[,1]); apply(apply(JKpw, MARGIN = 2, summary), MARGIN = 1, sd)
summary(JKpF[,1]); apply(apply(JKpF, MARGIN = 2, summary), MARGIN = 1, sd)
summary(JKps1w[,1]); apply(apply(JKps1w, MARGIN = 2, summary), MARGIN = 1, sd)
summary(JKps2w[,1]); apply(apply(JKps2w, MARGIN = 2, summary), MARGIN = 1, sd)
summary(JKptil1[,1]); apply(apply(JKptil1, MARGIN = 2, summary), MARGIN = 1, sd)
summary(JKptil2[,1]); apply(apply(JKptil2, MARGIN = 2, summary), MARGIN = 1, sd)

save(JKpF, JKpw, JKps1w, JKps2w, JKptil1, JKptil2, JKbeta, JKcoef, file = "Jack_ss_Dt.RData")
